package com.acane.instagram.feature.register

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.acane.instagram.R
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.LightGrayBackground
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun RegisterRoute(
    registerViewModel: RegisterViewModel = viewModel(),
    navController: NavController,
    toLogin: () -> Unit,

) {
    RegisterScreen(
        registerViewModel = registerViewModel,
        navController = navController,
        toLogin = toLogin,
    )
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun RegisterScreen(
    registerViewModel: RegisterViewModel,
    navController: NavController,
    toLogin: () -> Unit,
) {
    val isEmailRegister by remember { mutableStateOf(false) }
    val isPhoneRegister by remember { mutableStateOf(false) }

    val phoneNumber = registerViewModel.phoneNumber.collectAsState()
    val email = registerViewModel.email.collectAsState()
    val context = LocalContext.current
    // 获取软键盘控制器
    val keyboardController = LocalSoftwareKeyboardController.current
    val registerBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val userName = registerViewModel.userName.collectAsState()
    val password = registerViewModel.password.collectAsState()
    val confirmPassword = registerViewModel.confirmPassword.collectAsState()
    val pagerState = com.google.accompanist.pager.rememberPagerState(initialPage = 0)
    val scope = rememberCoroutineScope()
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "输入手机号或邮箱",
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
                        color = Color.Black,
                    )
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Icon(Icons.Default.ArrowBack, null)
                    }
                },
                actions = {

                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White
                ),
            )
        },
        containerColor = Color.White,
    ) { padding ->
        Column(
            modifier = Modifier.padding(padding)
        ) {
            val titles: List<String> = listOf(
                "电话", "发邮件"
            )

            Column(
                modifier = Modifier
                    .fillMaxSize()
            ) {
                TabRow(
                    selectedTabIndex = pagerState.currentPage,
                    containerColor = Color.White,
                    tabs = {
                        titles.forEachIndexed { index, title ->
                            Tab(
                                modifier = Modifier.padding(10.dp),
                                selected = pagerState.currentPage == index,
                                onClick = {
                                    scope.launch {
                                        pagerState.animateScrollToPage(index)
                                    }
                                },
                            ) {
                                Text(
                                    text = title,
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                )
                            }
                        }
                    }
                )


                // Pager
                com.google.accompanist.pager.HorizontalPager(
                    count = titles.size,
                    state = pagerState,
                    modifier = Modifier.padding(bottom = 30.dp)
                ) { page ->
                    when (page) {
                        0 -> PhoneNumberInput(
                            scope = scope,
                            registerViewModel = registerViewModel,
                            phoneNumber = phoneNumber.value,
                            registerBottomSheetState = registerBottomSheetState,
                            context = context,
                        )


                        1 -> EmailInput(
                            scope = scope,
                            registerViewModel = registerViewModel,
                            email = email.value,
                            registerBottomSheetState = registerBottomSheetState,
                            context = context,
                        )
                    }
                }
                Spacer(modifier = Modifier.weight(1.0f))
                // 分割线
                Divider(modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 20.dp))
                // 注册文本按钮
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 10.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = "已有帐户？",
                        color = InstagramDarkGray,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold
                    )
                    Spacer(modifier = Modifier.size(8.dp))
                    Text(
                        text = "登录",
                        color = InstagramBlue,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.clickable {
                            toLogin()
                        }
                    )
                }
            }
        }

    }

    ModalBottomSheetLayout(
        sheetState = registerBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
            ) {
                // 添加 Bar
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentSize(align = Alignment.Center)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.bar_horizontal),
                            contentDescription = "bar",
                        )
                    }
                }
                // 主要内容区域
                item {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        TextField(
                            value = userName.value,
                            onValueChange = {
                                registerViewModel.updateUserName(it)
                            },
                            label = {
                                Text(text = "帐户名")
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp)
                                .heightIn(min = 48.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                        TextField(
                            value = password.value,
                            onValueChange = {
                                registerViewModel.updatePassword(it)
                            },
                            label = {
                                Text(text = "密码")
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp)
                                .heightIn(min = 48.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                        TextField(
                            value = confirmPassword.value,
                            onValueChange = {
                                registerViewModel.updateConfirmPassword(it)
                            },
                            label = {
                                Text(text = "确认密码")
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp)
                                .heightIn(min = 48.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                        Button(
                            onClick = {
                                Log.d("LoginButton", "点击登录（协程外）") // 先验证这里能否打印
                                scope.launch {
                                    // 账户非空提醒
                                    if (userName.value.isEmpty() || password.value.isEmpty() || confirmPassword.value.isEmpty()) {
                                        Toast.makeText(context, "请填写完整信息", Toast.LENGTH_SHORT).show()
                                        return@launch
                                    } else if (password.value != confirmPassword.value) {
                                        Toast.makeText(
                                            context,
                                            "两次密码不一致",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    } else {
                                        registerBottomSheetState.hide()
                                        registerViewModel.register(
                                            userName = userName.value,
                                            password = password.value,
                                            email = email.value,
                                            phoneNumber = phoneNumber.value
                                        )

                                        Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT)
                                            .show()
                                        toLogin()
                                    }
                                }
                            },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = InstagramBlue,
                                contentColor = Color.White
                            ),
                            modifier = Modifier
                                .height(60.dp)
                                .padding(horizontal = 8.dp)
                                .fillMaxWidth(),
                            shape = RoundedCornerShape(5.dp),
                            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                        ) {
                            Text(
                                text = "完成注册",
                                fontSize = 16.sp,
                                color = Color.White,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }

                }
            }
        }) {}
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PhoneNumberInput(
    scope: CoroutineScope,
    registerViewModel: RegisterViewModel,
    phoneNumber: String,
    registerBottomSheetState: ModalBottomSheetState,
    context: Context,
) {
    // 获取软键盘控制器
    val keyboardController = LocalSoftwareKeyboardController.current
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        Spacer(modifier = Modifier.size(10.dp))
        TextField(
            value = phoneNumber,
            onValueChange = {
                registerViewModel.updatePhoneNumber(it)
            },
            label = {
                Text(text = "手机号")
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
                .padding(start = 8.dp, end = 8.dp)
                .heightIn(min = 48.dp, max = 56.dp),
            colors = TextFieldDefaults.colors(
                focusedIndicatorColor = LightGrayBackground,
                unfocusedIndicatorColor = LightGrayBackground,
                disabledIndicatorColor = LightGrayBackground,
                unfocusedContainerColor = LightGrayBackground,
            ),
            shape = RoundedCornerShape(5.dp),
        )
        Spacer(modifier = Modifier.size(10.dp))
        Button(
            onClick = {
                if (phoneNumber.isBlank()) {
                    Toast.makeText(
                        context,
                        "手机号不能为空",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@Button
                }
                Log.d("LoginButton", "点击登录（协程外）") // 先验证这里能否打印
                scope.launch {
                    keyboardController?.hide()
                    Log.d("LoginButton", "协程启动") // 验证协程是否正常启动
                    registerBottomSheetState.show()
                }
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = InstagramBlue,
                contentColor = Color.White
            ),
            modifier = Modifier
                .height(60.dp)
                .padding(horizontal = 8.dp)
                .padding(start = 8.dp, end = 8.dp)
                .fillMaxWidth(),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
        ) {
            Text(
                text = "继续",
                fontSize = 16.sp,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }


}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun EmailInput(
    scope: CoroutineScope,
    registerViewModel: RegisterViewModel,
    email: String,
    registerBottomSheetState: ModalBottomSheetState,
    context: Context,
) {
    // 获取软键盘控制器
    val keyboardController = LocalSoftwareKeyboardController.current
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        Spacer(modifier = Modifier.size(10.dp))
        TextField(
            value = email,
            onValueChange = {
                registerViewModel.updateEmail(it)
            },
            label = {
                Text(text = "邮箱")
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp)
                .padding(start = 8.dp, end = 8.dp)
                .heightIn(min = 48.dp, max = 56.dp),
            colors = TextFieldDefaults.colors(
                focusedIndicatorColor = LightGrayBackground,
                unfocusedIndicatorColor = LightGrayBackground,
                disabledIndicatorColor = LightGrayBackground,
                unfocusedContainerColor = LightGrayBackground,
            ),
            shape = RoundedCornerShape(5.dp),
        )
        Spacer(modifier = Modifier.size(10.dp))
        Button(
            onClick = {
                if (email.isBlank()) {
                    Toast.makeText(
                        context,
                        "邮箱不能为空",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@Button
                }
                Log.d("LoginButton", "点击登录（协程外）") // 先验证这里能否打印
                scope.launch {
                    Log.d("LoginButton", "协程启动") // 验证协程是否正常启动
                    keyboardController?.hide()
                    registerBottomSheetState.show()
                }
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = InstagramBlue,
                contentColor = Color.White
            ),
            modifier = Modifier
                .height(60.dp)
                .padding(horizontal = 8.dp)
                .padding(start = 8.dp, end = 8.dp)
                .fillMaxWidth(),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
        ) {
            Text(
                text = "继续",
                fontSize = 16.sp,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }

}